package com.asia5b.a5mall.member.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.member.R
import com.asia5b.a5mall.member.databinding.ActivityPersoninfoBinding
import com.asia5b.a5mall.member.fragment.SelectRegion2DF
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.config.UserRepository
import com.asia5b.a5mall.middleware.logic.viewmodel.member.PersonInfoActivityVM
import com.asia5b.a5mall.middleware.model.member.AddressModel
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.BaseTextWatcher
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_personinfo.*

/**
 * Created by zhangyuncai on 2019/12/30.
 * 个人信息
 */
@Route(path = ActCons.PersonInfoActivity)
class PersonInfoActivity : SimpleActivity<PersonInfoActivityVM, ActivityPersoninfoBinding>() {
    override val viewModelClazz: Class<PersonInfoActivityVM>
        get() = PersonInfoActivityVM::class.java

    override fun getDataBinding(): ActivityPersoninfoBinding {
        return ActivityPersoninfoBinding.inflate(layoutInflater)
    }

    override var sIsDark = true

    //选择性别
    val sexes by lazy { mutableListOf<String>(getString(R.string.女), getString(R.string.男)) }
    var memberInfo = UserRepository.getUserInfo()


    override fun initView() {
        memberInfo = UserRepository.getUserInfo()
        setMemberInfoView()
    }

    fun setMemberInfoView() {
        mDataBinding.data = memberInfo
        setMemberFaceView()
    }

    fun setMemberFaceView() {
        WImageLoader.displayImage(memberInfo.face, iv_personinfo_face, R.drawable.ic_userface)
    }

    override fun initEvent() {
        //保存
        head_personinfo.tv_title_righttxt.setOnClickListener {
            val emial = et_personinfo_email.text.toString().trim()
            if (!WValidatorUtil.isEmail(emial)) {
                showMessage(R.string.邮箱格式不对)
                return@setOnClickListener
            }
            InputMethodUtils.closeKeyBoard(mActivity)
            if (UserRepository.isLogin(mActivity)) {
                mViewModel.editMember(memberInfo)
            }
        }
        //头像
        ll_personinfo_face.setOnClickListener {
            RxPermissions(mActivity)
                    .request(Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe {
                        if (it) {
                            openPicture(callback = object :OnResultCallbackListener<LocalMedia>{
                                override fun onResult(selectList: MutableList<LocalMedia>?) {
                                    if (!selectList.isNullOrEmpty()) {
                                        val localMedia = selectList[0]
                                        val path = localMedia.compressPath
                                        if (!TextUtils.isEmpty(path)) {
                                            mViewModel.uploader(path)
                                        }
                                    }
                                }

                                override fun onCancel() {
                                }

                            })
                        }
                    }
        }
        //性别
        ll_personinfo_sex.setOnClickListener {
            InputMethodUtils.closeKeyBoard(mActivity)
            val pickerView = OptionsPickerBuilder(mActivity, OnOptionsSelectListener { options1, options2, options3, v ->
                memberInfo.sex = options1
                setMemberInfoView()
            }).build<String>()
            pickerView.setPicker(sexes)
            pickerView.show()
        }
        //出生日期
        ll_personinfo_birthday.setOnClickListener {
            InputMethodUtils.closeKeyBoard(mActivity)
            TimePickerBuilder(mActivity) { date, view ->
                memberInfo.birthday = date.time
                setMemberInfoView()
            }.build().show(true)
        }
        //地区
        ll_personinfo_area.setOnClickListener {
            InputMethodUtils.closeKeyBoard(mActivity)
            val selectRegion2DF = SelectRegion2DF()
            val addressModel = AddressModel()
            addressModel.countryName = memberInfo.pro
            addressModel.countryId = memberInfo.proId
            addressModel.provinceName = memberInfo.city
            addressModel.provinceId = memberInfo.cityId
            addressModel.cityName = memberInfo.county
            addressModel.cityId = memberInfo.countyId
            addressModel.townName = memberInfo.town
            addressModel.townId = memberInfo.townId
            selectRegion2DF.selectAddressModel = addressModel
            selectRegion2DF.show(supportFragmentManager, "selectRegion2DF")
            selectRegion2DF.setSureClick<AddressModel> {selectAddressModel->
                if (selectAddressModel != null) {
                    //国家/州/城市/城镇 并不是一一对应
                    memberInfo.pro = selectAddressModel.countryName
                    memberInfo.proId = selectAddressModel.countryId
                    memberInfo.city = selectAddressModel.provinceName
                    memberInfo.cityId = selectAddressModel.provinceId
                    memberInfo.county = selectAddressModel.cityName
                    memberInfo.countyId = selectAddressModel.cityId
                    memberInfo.town = selectAddressModel.townName
                    memberInfo.townId = selectAddressModel.townId
                    setMemberInfoView()
                }
            }
        }
        //昵称
        et_personinfo_nickname.addTextChangedListener(object : BaseTextWatcher() {
            override fun onTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {
                super.onTextChanged(charSequence, start, count, after)
                memberInfo.nikename = "${charSequence}"
            }
        })
        //详细地址
        et_personinfo_detail.addTextChangedListener(object : BaseTextWatcher() {
            override fun onTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {
                super.onTextChanged(charSequence, start, count, after)
                memberInfo.address = "${charSequence}"
            }
        })
        //电子邮箱
        et_personinfo_email.addTextChangedListener(object : BaseTextWatcher() {
            override fun onTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {
                super.onTextChanged(charSequence, start, count, after)
                memberInfo.email = "${charSequence}"
            }
        })
    }

  override  fun startObserver()
    {
        mViewModel.editMemberResultLiveData.observe(this, Observer {
            editMemberResult()
        })
        mViewModel.uploaderLiveData.observe(this, Observer {
            if (!TextUtils.isEmpty(it)) {
                memberInfo.face = it
                WImageLoader.displayImage(it, iv_personinfo_face, R.drawable.ic_userface)
            }
        })
    }

    override fun initData() {

    }

    fun editMemberResult() {
        pop()
    }

}